//
//  JsonToObject.m
//  SWCommonFrame
//
//  Created by shaowei on 13-6-14.
//  Copyright (c) 2013年 shaowei. All rights reserved.
//

#import "JsonToObject.h"
#import <objc/runtime.h>
#import "JSONKit.h"

@implementation JsonToObject


#pragma mark - Function - Public

+ (NSArray *)convertObjectFromJsonString:(NSString *)jsonStr{
    if (!jsonStr.length) {
        NSAssert(0, @"json->对象,jsonStr参数，为空");
        return nil;
    }
    NSDictionary *objsDict=[jsonStr objectFromJSONString];
    return [JsonToObject convertObjectFromDic:objsDict];
}

+ (NSArray *)convertObjectFromJsonData:(NSData *)jsonData{
    if (!jsonData) {
        NSAssert(0, @"json->对象,jsonData参数，为空");
        return nil;
    }
    NSDictionary *objsDict=[jsonData objectFromJSONData];
    return [JsonToObject convertObjectFromDic:objsDict];
}


#pragma mark Function - Private

/**
 转换字典、数组-》对象,即将JSON字符串映射到Model对象
 @param jsonStr：原始字典数据，
 @returns Model对象数组
 */
+ (NSArray *)convertObjectFromDic:(NSDictionary *)objsDict{
    
    if (objsDict==nil) {
        DLog(@"SW - json->对象,字典参数，为空");
        return nil;
    }
    
    NSMutableArray *objModelArray = [[NSMutableArray alloc] initWithCapacity:[objsDict count]+1];
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    //JSON字符串到Model对象的映射
    
    for (NSString *objName in objsDict.allKeys) {
        NSArray *objArray=[objsDict objectForKey:objName];
        for (int k=0;k<objArray.count;k++) {
            //遍历所有对象，放入数组中
            Class objModelClass=NSClassFromString(objName);
            NSObject *objModel=[[objModelClass alloc] init];
            SWASSERT(objModel, @"model类:%@,不存在",objName);
            NSArray *propertyArray=[[objArray objectAtIndex:k] allKeys];
            
            for (NSString *propertyName in propertyArray) {
                objc_property_t property_t = class_getProperty(objModelClass, [propertyName UTF8String]);
                if (property_t != NULL) {
                    id propertyValue=[[objArray objectAtIndex:k] objectForKey:propertyName];
                    [objModel setValue:propertyValue forKey:propertyName];
                }
            }
            
            @try {
                [objModelArray addObject:objModel];
            }
            @catch (NSException *exception) {
                DTLog(exception);
            }
            
            
            [objModel release];
        }
    }
    
    [pool release];
    
    return [objModelArray autorelease];
}

@end
